import { Provide } from "@midwayjs/core";
import { Chapter, ChapterContent, Novel } from "../entity/novel.entity";
import { Repository } from "typeorm";
import { InjectEntityModel } from '@midwayjs/typeorm';

@Provide()
export class NovelService {

    @InjectEntityModel(Novel)
    novelModel: Repository<Novel>;

    @InjectEntityModel(Chapter)
    chapterRepository: Repository<Chapter>;

    @InjectEntityModel(ChapterContent)
    chapterContentRepository: Repository<ChapterContent>;

    // 查询全部
    async findNovel(): Promise<Novel[]> {
        return this.novelModel.find({});
    }

    // 模糊搜索
    async likeNovel(title: string): Promise<Novel[]> {
        return this.novelModel.createQueryBuilder("novel").where("title like %" + title + "%").getMany();
    }
    //根据ID查询
    async findNovelById(id: number): Promise<Novel> {
        return this.novelModel.findOneBy({
            id: id
        });
    }
    //添加小说
    async addNovel(novel: Novel) {
        this.novelModel.save(novel)

    }
    //更新小说
    async updateNovel(novel: Novel) {
        this.novelModel.update({ id: novel.id }, novel)

    }

    //根据ID删除
    async removeNovelById(id: number) {
        let novel = await this.findNovelById(id);
        novel.isDelete = true;
        this.novelModel.save(novel);
    }

    //查找所有章节 根据小说ID
    async findAllChapterByNovelId(novelId: number): Promise<Chapter[]> {
        return this.chapterRepository.findBy({
            novelId: novelId
        })
    }
    //查找章节 根据ID
    async findChapterById(id: number): Promise<Chapter> {
        return this.chapterRepository.findOneBy({
            id: id
        })
    }
    //查找章节内容 根据ID
    async findChapterContentById(id: number): Promise<ChapterContent> {
        return this.chapterContentRepository.findOneBy({
            id: id
        })
    }

    //添加章节
    async addChapter(chapter: Chapter, chapterContent: ChapterContent) {
        this.chapterRepository.save(chapter)
        this.chapterContentRepository.save(chapterContent)
    }
    //逻辑删除小说 根据ID
    async removeChapterById(id: number) {
        let chapter = await this.findChapterById(id);
        chapter.isDelete = true;
        this.chapterRepository.save(chapter)
    }

    //更新章节
    async updateChapter(chapter: Chapter, chapterContent: ChapterContent) {
        this.chapterRepository.update({ id: chapter.id }, chapter)
        this.chapterContentRepository.update({ id: chapter.id }, chapterContent)
    }
}